* Creates connected set for 2009 period onwards (used to create Table A3 and Figure A4)
clear all

use "$savedata/ami_analysis_mainspef.dta", clear

drop if derv_age<35
keep if finyear>2008

* Impose minimum volume restrictions on each hospital
egen hosp_vol_year = sum(ami), by(trust_code finyear)

* Treat at least 100 heart attack patients in a year to be included in the data
keep if hosp_vol_year>99

egen vol = sum(ami), by(pconsult)
egen vol_trust = sum(ami), by(pconsult trust_code)

drop if vol_trust<10

egen vol_year = sum(ami), by(pconsult finyear)

egen vol_trust_year = sum(ami), by(pconsult trust_code finyear)

* Restrictions based on different number of minimum patients treated by a consultant-hospital combination

foreach x in 10 25 50 100{
	
preserve
* Only want to be linked by docs who treat x or more patients in a given hospital
collapse (sum) ami, by(trust_code pconsult)

* This is new as of 14th July 2024
keep if ami>=`x'

egen constotal = sum(ami), by(pconsult)
rename ami trust_constotal
*egen trust_constotal = sum(ami), by(pconsult trust_code)

* How to connect?
** start with connection being that doctors work in at least 2 hospitals; with a minimum volume in total

* Number of hospitals worked in a given year
bys pconsult: gen x=_n
egen total_trusts_worked_in = max(x), by(pconsult)

* Keep only the connectors (those in more than one hospital in a given year)
keep if total_trusts>1

* Now keep only those who do a minimum of 10 or more
keep if trust_constotal>`x'

* for graphs, want to plot these
egen mincheck = min(trust_constotal), by(pconsult)
egen maxcheck = max(trust_constotal), by(pconsult)

* This is the original connected set

gen akm_set_mainspef`x' = 1
gen akm_connectors`x' = 1
egen akm_connecting_pats`x' = sum(trust_constotal), by(trust_code)

collapse (max) akm_set_mainspef`x' (sum) akm_connectors`x' akm_connecting_pats`x', by(trust_code)

save "$savedata/connect_total`x'_09onwards.dta", replace
count

restore
}
